import apiClient from "@/lib/request";
import FlightsChart from "./flights-chart";
import { BarChartData, ChartProps } from "./flights-chart.interface";
import { MonthFlights, Result } from "@/lib/dto";
// const totalFlights = [632, 524, 544, 601, 644, 674, 673, 653, 624, 567, 726, 0];
const irregularityRage = [
  3.82, 4.65, 3.69, 0, 0, 3.55, 7.07, 3.58, 15.15, 16.81, 0, 0,
];

const fetchChartData = async () => {
  try {
    const res: Result<MonthFlights[]> = await apiClient.get(
      "flight/total-flight/monthly-flights/2024/01/12"
    );
    return res.data;
  } catch (error) {
    // 抛出错误信息
    throw new Error("Error fetching data");
  }
};

const dataPrepare = (data: number[]): ChartProps => {
  const chartProps: ChartProps = {
    isTotal: false,
    trending: 0,
    data: [],
    isIncrease: false,
  };
  // 获取当前月份-1个月
  const month = new Date().getMonth() - 1;
  chartProps.trending = data[month] - data[month - 1];
  chartProps.isIncrease = chartProps.trending > 0 ? true : false;
  chartProps.trending = Math.abs(chartProps.trending);
  for (let i = 0; i < data.length; i++) {
    const chartData: BarChartData = {
      month: `${i + 1}月`,
      lineData: data[i],
      barData: data[i],
    };
    chartProps.data.push(chartData);
  }

  return chartProps;
};
const OperationCharts = async ({ ...props }) => {
  const totalFlightsList = await fetchChartData();

  if (!totalFlightsList) return <div>加载中...</div>;
  // 取出每个月的航班总数
  const totalFlights = totalFlightsList.map((item: MonthFlights) => item.total);
  const flightsChartProps = dataPrepare(totalFlights);
  const irregularityRageChartProps = dataPrepare(irregularityRage);

  return (
    <div
      {...props}
      className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-2 gap-4"
    >
      <FlightsChart
        isTotal={true}
        trending={flightsChartProps.trending}
        data={flightsChartProps.data}
        isIncrease={flightsChartProps.isIncrease}
      />
      <FlightsChart
        isTotal={false}
        trending={irregularityRageChartProps.trending}
        data={irregularityRageChartProps.data}
        isIncrease={irregularityRageChartProps.isIncrease}
      />
    </div>
  );
};

export default OperationCharts;
